package com.ITXu.reggie.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ITXu.reggie.commom.R;
import com.ITXu.reggie.entity.Category;
import com.ITXu.reggie.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/category")
public class CategoryController {

	@Autowired
	public CategoryService categoryService;
	
	@PostMapping
	public R<String> save(@RequestBody Category category) {
		categoryService.save(category);
		return R.success("新增分类成功");
	}
	
	@GetMapping("/page")
	public R<Page> page(int page, int pageSize){
		//构造分页构造器
	    Page<Category> pageInfo = new Page<>();
		//构造查询构造器
	    LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
	    //给查询构造器输入查询条件
	    queryWrapper.orderByDesc(Category::getSort);
		//调用CategoryService的方法
	    categoryService.page(pageInfo, queryWrapper);
		return R.success(pageInfo);
	}
	
	@DeleteMapping
	public R<String> delete(Long ids) {
		log.info("删除分类，id为{}", ids);
		categoryService.remove(ids);
		return R.success("分类信息删除成功");
	}
	
	@GetMapping("/list")
	public R<List<Category>> list(Category category) {
		//构造查询构造器
		LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
		//设置查询条件
		queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
		queryWrapper.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
		//注入查询条件
		List<Category> list = categoryService.list(queryWrapper);
		return R.success(list);
	}
	
	
}
